﻿using System;
using System.Windows.Forms;
using System.Data;
using Gencode.PrsCommon.Data.Person;

namespace Gencode.PrsUtil.Controls
{
	public class PUPersonComboBox : ComboBox
	{
		DataView m_personen;

		public PUPersonComboBox()
			: base()
		{
		}

		protected override void InitLayout()
		{
			base.InitLayout();
		}

		public void InitData(string mandid)
		{
			m_mandid = mandid;
			RefreshData();
		}

		public void RefreshData()
		{
			m_personen = PersonData.GetPersonen(Mandid, Typ, true);
			DataSource = m_personen;
			DisplayMember = "anzeigename";
		}

		protected override void Dispose(bool disposing)
		{
			if (m_personen != null)
				m_personen.Dispose();
			base.Dispose(disposing);
		}

		string m_mandid = "";
		public string Mandid
		{
			private get
			{
				return m_mandid;
			}
			set
			{
				m_mandid = value;
			}
		}

		PersonTyp m_typ = PersonTyp.Stammperson;
		public PersonTyp Typ
		{
			get
			{
				return m_typ;
			}
			set
			{
				m_typ = value;
			}
		}

		public void SetIndexAt(int prsid)
		{
			if (prsid >= 0)
			{
				for (int i = 0; i < m_personen.Count; i++)
				{
					if (m_personen[i].Row["prsid"].ToString() != string.Empty)
					{
						if (int.Parse(m_personen[i].Row["prsid"].ToString()) == prsid)
						{
							SelectedIndex = i;
							i = m_personen.Count;
						}
					}
				}
			}
			else
				SelectedIndex = -1;
		}

		public int SelectedPrsID
		{
			get
			{
				if (SelectedIndex >= 0 &&
					m_personen[SelectedIndex].Row["PrsID"].ToString() != null &&
					m_personen[SelectedIndex].Row["PrsID"].ToString() != string.Empty)
					return int.Parse(m_personen[SelectedIndex].Row["PrsID"].ToString());

				return 0;
			}
		}
	}
}
